package com.jack.bookshop.filter;

import com.jack.bookshop.vo.UserVo;
import jakarta.servlet.*;
import jakarta.servlet.annotation.*;
import jakarta.servlet.http.HttpFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import java.io.IOException;
import java.io.PrintWriter;

@WebFilter(
        filterName="SigninFilter",
        urlPatterns={"/cart.do","/cart.jsp"}
)
public class SigninFilter extends HttpFilter implements Filter {
    private static final long serialVersionUID = 1L;

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        HttpSession session = req.getSession();
        UserVo userVo = (UserVo)session.getAttribute("userVo");
        if(userVo==null||userVo.getId()==0) {
            StringBuffer sb = new StringBuffer();
            sb.append("<script>");
            sb.append("alert('Please Sign In First!');");
            sb.append("window.location='" + req.getHeader("Referer") + "';");
            sb.append("</script>");
            PrintWriter out = res.getWriter();
            out.append(sb.toString());
            out.flush();
            out.close();
        }else {
            chain.doFilter(request, response);
        }
    }

    public void init(FilterConfig fConfig) throws ServletException {
    }

    public SigninFilter() {
        super();
    }

    public void destroy() {
    }

}


